﻿using System;
using System.Collections.Generic;
using System.Reflection;

using ActiveDocument.Attributes;

using Lucene.Net.Documents;

namespace ActiveDocument.Persistence
{
    public class ActiveDocumentRestorer
    {
        public static T ConvertFromDocument<T>(Document d) where T : class, new()
        {
            object t = Assembly.GetAssembly(typeof(T)).CreateInstance(typeof(T).Name);

            foreach (PropertyInfo inf in typeof(T).GetProperties())
            {
                object[] att = inf.GetCustomAttributes(false);
                for (int i = 0; i < att.Length; i++)
                {
                    if (att[i].GetType() == typeof(IndexedAttribute))
                    {
                        string sv = d.GetField(inf.Name).StringValue();
                        object val = sv;

                        if(inf.PropertyType == typeof(bool))
                            val = bool.Parse(sv);
                        else if(inf.PropertyType == typeof(byte))
                            val = byte.Parse(sv);
                        else if(inf.PropertyType == typeof(char))
                            val = char.Parse(sv);
                        else if(inf.PropertyType == typeof(decimal))
                            val = decimal.Parse(sv);
                        else if(inf.PropertyType == typeof(double))
                            val = double.Parse(sv);
                        else if(inf.PropertyType == typeof(Enum))
                            val = Enum.Parse(inf.PropertyType, sv);
                        else if(inf.PropertyType == typeof(float))
                            val = float.Parse(sv);
                        else if(inf.PropertyType == typeof(int))
                            val = int.Parse(sv);
                        else if(inf.PropertyType == typeof(long))
                            val = long.Parse(sv);
                        else if(inf.PropertyType == typeof(sbyte))
                            val = sbyte.Parse(sv);
                        else if(inf.PropertyType == typeof(short))
                            val = short.Parse(sv);
                        else if(inf.PropertyType == typeof(uint))
                            val = uint.Parse(sv);
                        else if(inf.PropertyType == typeof(ulong))
                            val = ulong.Parse(sv);
                        else if(inf.PropertyType == typeof(ushort))
                            val = ushort.Parse(sv);
                        inf.SetValue(t, val, null);
                    }
                }
            }
            
            return (T)t;
        }

    }
}
